const getOpenId = require("./getOpenId/index");
const getMiniProgramCode = require("./getMiniProgramCode/index");
const createCollection = require("./createCollection/index");
const selectRecord = require("./selectRecord/index");
const updateRecord = require("./updateRecord/index");
const sumRecord = require("./sumRecord/index");
const fetchGoodsList = require("./fetchGoodsList/index");
const genMpQrcode = require("./genMpQrcode/index");
const getSessionId = require("./getSessionId/index");
const login = require("./login/index");
// --- 添加：引入 saveUserInfo ---
const saveUserInfo = require("./saveUserInfo/index");
// --- 添加结束 ---
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});
const db = cloud.database(); // <--- 必须加上这行
// 云函数入口函数
exports.main = async (event, context) => {
  console.log("云函数入口收到参数:", JSON.stringify(event));
  console.log("云函数入口上下文:", JSON.stringify(context));

  try {
    if (!event.type) {
      console.error("缺少type参数");
      return {
        code: 400,
        msg: "缺少type参数",
        data: null,
      };
    }

    let result;

    switch (event.type) {
      case "getOpenId":
        result = await getOpenId.main(event, context);
        break;
      case "getMiniProgramCode":
        result = await getMiniProgramCode.main(event, context);
        break;
      case "createCollection":
        result = await createCollection.main(event, context);
        break;
      case "selectRecord":
        result = await selectRecord.main(event, context);
        break;
      case "updateRecord":
        result = await updateRecord.main(event, context);
        break;
      case "sumRecord":
        result = await sumRecord.main(event, context);
        break;
      case "fetchGoodsList":
        result = await fetchGoodsList.main(event, context);
        break;
      case "genMpQrcode":
        result = await genMpQrcode.main(event, context);
        break;
      case "getSessionId":
        console.log("处理getSessionId请求");
        result = await getSessionId.main(event.data, context);
        break;
      case "login":
        console.log("处理login请求，参数:", JSON.stringify(event));
        if (!event.data) {
          console.error("login请求缺少data参数");
          return {
            code: 400,
            msg: "缺少data参数",
            data: null,
          };
        }
        // 调用login子函数
        result = await login.main(event.data, context);
        console.log("login处理结果:", JSON.stringify(result));
        break;

      // 获取菜谱分类
      case "getRecipeCategories":
        console.log("处理getRecipeCategories请求");
        result = {
          code: 200,
          data: {
            list: [
              { id: "breakfast", name: "早餐" },
              { id: "lunch", name: "午餐" },
              { id: "dinner", name: "晚餐" },
              { id: "snack", name: "小食" },
              { id: "soup", name: "汤品" },
              { id: "vegetable", name: "素食" },
            ],
          },
          msg: "获取成功",
        };
        break;

      // 获取菜谱列表
      case "getRecipeList":
        console.log("处理getRecipeList请求");
        // 从参数中获取分页和筛选条件
        const { page = 1, pageSize = 10, category = "" } = event.data || {};

        // 返回模拟数据
        const mockRecipes = [
          {
            id: 1,
            title: "营养早餐三明治",
            imageUrl: "/images/discovers/png/sanmingzhi.png",
            description: "健康美味的三明治，含有丰富的蛋白质和维生素",
            calories: 350,
            cookingTime: "15分钟",
            difficulty: "简单",
            category: "早餐",
          },
          {
            id: 2,
            title: "清炒时蔬",
            imageUrl: "/images/discovers/png/qingjiaoshishu.png",
            description: "低脂健康的素食选择，富含膳食纤维",
            calories: 200,
            cookingTime: "20分钟",
            difficulty: "简单",
            category: "素食",
          },
          {
            id: 3,
            title: "养生排骨汤",
            imageUrl: "/images/discovers/png/paigutang.png",
            description: "滋补养生的排骨汤，营养丰富",
            calories: 450,
            cookingTime: "60分钟",
            difficulty: "中等",
            category: "汤品",
          },
        ];

        // 根据分类筛选
        let filteredRecipes = category
          ? mockRecipes.filter((recipe) => recipe.category === category)
          : mockRecipes;

        result = {
          code: 200,
          data: {
            list: filteredRecipes,
            total: filteredRecipes.length,
            page,
            pageSize,
          },
          msg: "获取成功",
        };
        break;

      // 搜索菜谱
      case "searchRecipes":
        console.log("处理searchRecipes请求");
        const searchParams = event.data || {};
        const { keyword = "", category: searchCategory = "" } = searchParams;

        // 模拟搜索结果
        const searchResult = {
          id: 1,
          title: "健康" + keyword + "食谱",
          imageUrl: "/images/recipes/healthy.jpg",
          description: "这是一道健康美味的" + keyword + "菜品",
          calories: 300,
          cookingTime: "30分钟",
          difficulty: "简单",
          category: "健康菜",
        };

        result = {
          code: 200,
          data: {
            list: [searchResult],
            total: 1,
            page: searchParams.page || 1,
            pageSize: searchParams.pageSize || 10,
          },
          msg: "搜索成功",
        };
        break;

      // 获取推荐套餐
      case "getRecommendedMeals": {
        console.log("处理getRecommendedMeals请求");

        result = {
          code: 200,
          data: {
            list: {
              breakfast: [
                {
                  id: 1,
                  name: "活力早餐套餐",
                  image: "/images/meals/breakfast1.png",
                  description: "营养均衡的健康早餐，提供一天所需能量",
                  calories: 350,
                  price: 29.9,
                  nutrition: {
                    protein: 20,
                    carbs: 40,
                    fat: 12,
                  },
                  type: "breakfast",
                },
                {
                  id: 2,
                  name: "轻食早餐套餐",
                  image: "/images/meals/breakfast2.png",
                  description: "低脂高纤维的清爽早餐",
                  calories: 280,
                  price: 25.9,
                  nutrition: {
                    protein: 15,
                    carbs: 35,
                    fat: 8,
                  },
                  type: "breakfast",
                },
              ],
              lunch: [
                {
                  id: 3,
                  name: "健康减脂午餐",
                  image: "/images/meals/lunch1.png",
                  description: "专为减脂人士定制的营养均衡午餐",
                  calories: 450,
                  price: 39.9,
                  nutrition: {
                    protein: 30,
                    carbs: 45,
                    fat: 15,
                  },
                  type: "lunch",
                },
                {
                  id: 4,
                  name: "能量午餐套餐",
                  image: "/images/meals/lunch2.png",
                  description: "提供充足能量的营养午餐",
                  calories: 520,
                  price: 42.9,
                  nutrition: {
                    protein: 35,
                    carbs: 50,
                    fat: 18,
                  },
                  type: "lunch",
                },
              ],
              dinner: [
                {
                  id: 5,
                  name: "轻享晚餐套餐",
                  image: "/images/meals/dinner1.png",
                  description: "易消化的健康晚餐",
                  calories: 380,
                  price: 35.9,
                  nutrition: {
                    protein: 25,
                    carbs: 35,
                    fat: 12,
                  },
                  type: "dinner",
                },
                {
                  id: 6,
                  name: "增肌能量晚餐",
                  image: "/images/meals/dinner2.png",
                  description: "高蛋白质、中等碳水的增肌晚餐",
                  calories: 650,
                  price: 45.9,
                  nutrition: {
                    protein: 40,
                    carbs: 40,
                    fat: 20,
                  },
                  type: "dinner",
                },
              ],
            },
            nutritionTips: [
              {
                id: 1,
                icon: "/images/tips/water.png",
                title: "补充水分",
                content: "建议每天饮水2000ml，保持身体水分平衡",
              },
              {
                id: 2,
                icon: "/images/tips/vegetables.png",
                title: "增加蔬菜摄入",
                content: "每餐应包含不同颜色的蔬菜，保证营养均衡",
              },
              {
                id: 3,
                icon: "/images/tips/protein.png",
                title: "优质蛋白",
                content: "选择瘦肉、鱼类、蛋类等优质蛋白，促进肌肉修复",
              },
              {
                id: 4,
                icon: "/images/tips/timing.png",
                title: "规律进餐",
                content: "保持规律的三餐时间，避免暴饮暴食",
              },
            ],
          },
          msg: "获取成功",
        };
        break;
      }

      // 获取用户健康数据
      // case "getUserHealthData":
      //   console.log("处理getUserHealthData请求");

      //   // 获取用户OpenID
      //   const userContext = cloud.getWXContext();
      //   const userOpenId = userContext.OPENID;

      //   // 模拟健康数据
      //   const healthData = {
      //     height: 175,
      //     weight: 70,
      //     age: 30,
      //     gender: "male",
      //     bmi: 22.9,
      //     activityLevel: 1.4,
      //     healthGoal: "maintain",
      //     allergies: [],
      //   };

      //   result = {
      //     code: 200,
      //     data: healthData,
      //     msg: "获取成功",
      //   };
      //   break;

      case "getUserInfo": {
        console.log("处理getUserInfo请求，参数:", JSON.stringify(event));
        // 获取用户信息
        const wxContext = cloud.getWXContext();
        const token = event.data?.token || "";
        const openId = wxContext.OPENID;

        // 从数据库获取用户信息
        try {
          const userCollection = db.collection("users");

          // 查询用户信息
          const userQuery = await userCollection
            .where({
              openId: openId,
            })
            .get();

          if (userQuery.data.length > 0) {
            // 找到用户数据
            const userData = userQuery.data[0];

            // 返回用户信息
            result = {
              code: 200,
              data: {
                wechatUserDto: {
                  ...userData,
                  token: token || `${openId}_${Date.now()}`,
                },
              },
              msg: "获取成功",
            };
          } else {
            // 用户不存在，返回默认信息
            result = {
              code: 200,
              data: {
                wechatUserDto: {
                  userId: openId,
                  nickName: "微信用户",
                  avatarUrl:
                    "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
                  gender: 0,
                  country: "",
                  province: "",
                  city: "",
                  phoneNumber: "",
                  openId: openId,
                  token: token || `${openId}_${Date.now()}`,
                },
              },
              msg: "获取成功",
            };
          }
        } catch (err) {
          console.error("获取用户信息失败:", err);
          result = {
            code: 500,
            msg: "获取用户信息失败",
            data: null,
          };
        }
        break;
      }

      case "updateUserAvatar": {
        console.log("处理updateUserAvatar请求，参数:", JSON.stringify(event));

        try {
          const fileID = event.data?.fileID;
          if (!fileID) {
            result = {
              code: 400,
              msg: "缺少文件ID",
              data: null,
            };
            break;
          }

          // 这里应该将头像ID保存到数据库
          // 现在简单返回成功和文件ID
          result = {
            code: 200,
            msg: "头像更新成功",
            data: fileID,
          };
        } catch (err) {
          console.error("更新头像失败:", err);
          result = {
            code: 500,
            msg: "更新头像失败",
            data: null,
          };
        }
        break;
      }

      case "updateUserInfo": {
        console.log("处理updateUserInfo请求，参数:", JSON.stringify(event));

        try {
          const userInfo = event.data?.userInfo;
          const wxContext = cloud.getWXContext();
          const openId = wxContext.OPENID;

          if (!userInfo) {
            result = {
              code: 400,
              msg: "缺少用户信息",
              data: null,
            };
            break;
          }

          if (!openId) {
            result = {
              code: 401,
              msg: "无法获取用户OpenID",
              data: null,
            };
            break;
          }

          console.log("用户OpenID:", openId);
          console.log("待更新的用户信息:", userInfo);

          // 检查用户是否已存在
          const userCollection = db.collection("users");

          try {
            const existingUser = await userCollection
              .where({
                _openid: openId,
              })
              .get();

            console.log("查询现有用户结果:", existingUser);

            let dbResult;
            const updateTime = db.serverDate();

            if (existingUser.data.length > 0) {
              // 更新现有用户
              console.log("更新现有用户数据");
              dbResult = await userCollection
                .doc(existingUser.data[0]._id)
                .update({
                  data: {
                    name: userInfo.name,
                    gender: userInfo.gender,
                    age: userInfo.age,
                    height: userInfo.height,
                    weight: userInfo.weight,
                    activityLevelId: userInfo.activityLevelId,
                    dietPreferenceId: userInfo.dietPreferenceId,
                    updateTime,
                  },
                });
            } else {
              // 创建新用户
              console.log("创建新用户");
              dbResult = await userCollection.add({
                data: {
                  ...userInfo,
                  _openid: openId,
                  createTime: updateTime,
                  updateTime,
                },
              });
            }

            console.log("数据库操作结果:", dbResult);

            // 获取最新的用户数据
            const updatedUser = await userCollection
              .where({
                _openid: openId,
              })
              .get();

            if (updatedUser.data.length > 0) {
              result = {
                code: 200,
                msg: "用户信息更新成功",
                data: {
                  wechatUserDto: updatedUser.data[0],
                },
              };
            } else {
              throw new Error("无法获取更新后的用户信息");
            }
          } catch (dbError) {
            console.error("数据库操作失败:", dbError);
            throw new Error("数据库操作失败: " + dbError.message);
          }
        } catch (err) {
          console.error("更新用户信息失败:", err);
          result = {
            code: 500,
            msg: err.message || "更新用户信息失败",
            data: null,
          };
        }
        break;
      }

      case "sendVerificationCode": {
        console.log(
          "处理sendVerificationCode请求，参数:",
          JSON.stringify(event)
        );

        try {
          const phoneNumber = event.data?.phoneNumber;

          if (!phoneNumber) {
            result = {
              code: 400,
              msg: "缺少手机号",
              data: null,
            };
            break;
          }

          // 这里应该发送短信验证码
          // 现在简单返回成功
          result = {
            code: 200,
            msg: "验证码发送成功",
            data: {
              verifyCode: "123456", // 模拟验证码
            },
          };
        } catch (err) {
          console.error("发送验证码失败:", err);
          result = {
            code: 500,
            msg: "发送验证码失败",
            data: null,
          };
        }
        break;
      }

      // 获取套餐详情
      case "getMealDetails":
        console.log("处理getMealDetails请求，参数:", JSON.stringify(event));

        try {
          const mealId = event.data?.mealId;

          if (!mealId) {
            result = {
              code: 400,
              msg: "缺少套餐ID",
              data: null,
            };
            break;
          }

          // 从数据库获取套餐信息
          const db = cloud.database();

          // 查询套餐基本信息
          const mealQuery = await db.collection("meals").doc(mealId).get();

          if (!mealQuery.data) {
            result = {
              code: 404,
              msg: "套餐不存在",
              data: null,
            };
            break;
          }

          const meal = mealQuery.data;

          // 查询相关食材信息
          const _ = db.command;
          const ingredientsQuery = await db
            .collection("ingredients")
            .where({
              _id: _.in(meal.ingredientIds || []),
            })
            .get();

          // 查询营养师信息
          const nutritionist = meal.nutritionistId
            ? (
                await db
                  .collection("nutritionists")
                  .doc(meal.nutritionistId)
                  .get()
              ).data
            : null;

          // 组装完整数据
          const fullMealData = {
            ...meal,
            ingredients: ingredientsQuery.data || [],
            nutritionist: nutritionist || {},
          };

          result = {
            code: 200,
            success: true,
            data: fullMealData,
            msg: "获取成功",
          };
        } catch (err) {
          console.error("获取套餐详情失败:", err);
          result = {
            code: 500,
            success: false,
            msg: "获取套餐详情失败",
            data: null,
          };
        }
        break;

      // 创建订单
      case "createOrder":
        console.log("处理createOrder请求，参数:", JSON.stringify(event));

        try {
          const mealId = event.data?.mealId;
          const quantity = event.data?.quantity || 1;

          if (!mealId) {
            result = {
              code: 400,
              msg: "缺少套餐ID",
              data: null,
            };
            break;
          }

          // 获取用户信息
          const wxContext = cloud.getWXContext();
          const userOpenId = wxContext.OPENID;

          // 从数据库获取套餐信息计算价格
          const db = cloud.database();
          const mealQuery = await db.collection("meals").doc(mealId).get();

          if (!mealQuery.data) {
            result = {
              code: 404,
              msg: "套餐不存在",
              data: null,
            };
            break;
          }

          const meal = mealQuery.data;

          // 创建订单数据
          const orderData = {
            mealId,
            mealName: meal.name,
            price: meal.price,
            quantity,
            totalAmount: meal.price * quantity,
            userId: userOpenId,
            status: "pending", // 待支付
            createTime: Date.now(),
          };

          // 保存订单到数据库
          const orderResult = await db.collection("orders").add({
            data: orderData,
          });

          result = {
            code: 200,
            success: true,
            data: {
              orderId: orderResult._id,
              orderData,
            },
            msg: "订单创建成功",
          };
        } catch (err) {
          console.error("创建订单失败:", err);
          result = {
            code: 500,
            success: false,
            msg: "创建订单失败",
            data: null,
          };
        }
        break;

      // 初始化测试数据
      case "initTestData":
        console.log("处理initTestData请求");

        try {
          const db = cloud.database();

          // 清空测试集合
          const collections = [
            "meals",
            "ingredients",
            "nutritionists",
            "orders",
          ];
          for (const collection of collections) {
            try {
              // 获取所有数据的ID
              const dataQuery = await db.collection(collection).get();

              // 如果有数据则逐个删除
              for (const item of dataQuery.data) {
                await db.collection(collection).doc(item._id).remove();
              }

              console.log(`清空集合 ${collection} 成功`);
            } catch (err) {
              console.error(`清空集合 ${collection} 失败:`, err);
            }
          }

          // 添加测试数据 - 营养师
          const nutritionists = [
            {
              name: "王医生",
              title: "主任医师",
              avatar: "/images/nutritionists/doctor1.png",
              description: "从事临床营养工作多年，擅长个性化饮食方案定制",
              specialty: ["减脂", "增肌", "孕产营养"],
              hospital: "北京协和医院",
            },
            {
              name: "李营养师",
              title: "高级营养师",
              avatar: "/images/nutritionists/nutritionist1.png",
              description: "国家一级营养师，专注运动营养学研究",
              specialty: ["运动营养", "健身饮食", "体重管理"],
              hospital: "上海体育学院",
            },
          ];

          // 保存营养师数据
          for (const nutritionist of nutritionists) {
            await db.collection("nutritionists").add({
              data: nutritionist,
            });
          }

          // 获取营养师ID用于关联
          const nutritionistQuery = await db.collection("nutritionists").get();
          const nutritionistIds = nutritionistQuery.data.map(
            (item) => item._id
          );

          // 添加测试数据 - 食材
          const ingredients = [
            {
              name: "鸡胸肉",
              image: "/images/ingredients/chicken.png",
              category: "肉类",
              nutrition: {
                calories: 165,
                protein: 31,
                carbs: 0,
                fat: 3.6,
              },
              description: "优质蛋白质来源，脂肪含量低",
            },
            {
              name: "西兰花",
              image: "/images/ingredients/broccoli.png",
              category: "蔬菜",
              nutrition: {
                calories: 34,
                protein: 2.8,
                carbs: 6.6,
                fat: 0.4,
              },
              description: "富含维生素C和纤维素",
            },
            {
              name: "糙米",
              image: "/images/ingredients/brown-rice.png",
              category: "谷物",
              nutrition: {
                calories: 112,
                protein: 2.6,
                carbs: 23.5,
                fat: 0.9,
              },
              description: "丰富的膳食纤维和B族维生素",
            },
          ];

          // 保存食材数据
          for (const ingredient of ingredients) {
            await db.collection("ingredients").add({
              data: ingredient,
            });
          }

          // 获取食材ID用于关联
          const ingredientQuery = await db.collection("ingredients").get();
          const ingredientIds = ingredientQuery.data.map((item) => item._id);

          // 添加测试数据 - 套餐
          const meals = [
            {
              name: "健康减脂套餐",
              image: "/images/meals/healthy1.jpg",
              description: "专为减脂人士定制的营养均衡套餐",
              calories: 450,
              price: 39.9,
              nutrition: {
                protein: 30,
                carbs: 45,
                fat: 15,
              },
              nutritionistId: nutritionistIds[0],
              ingredientIds: [ingredientIds[0], ingredientIds[1]],
              mealType: "lunch",
              cookingSteps: [
                "鸡胸肉切片，用盐、胡椒腌制15分钟",
                "西兰花切小朵，焯水",
                "热锅少油，煎鸡胸肉至金黄",
                "加入西兰花翻炒均匀",
                "出锅前撒少许黑胡椒",
              ],
            },
            {
              name: "增肌能量套餐",
              image: "/images/meals/protein1.jpg",
              description: "高蛋白质、中等碳水的增肌套餐",
              calories: 650,
              price: 45.9,
              nutrition: {
                protein: 40,
                carbs: 40,
                fat: 20,
              },
              nutritionistId: nutritionistIds[1],
              ingredientIds: [ingredientIds[0], ingredientIds[2]],
              mealType: "dinner",
              cookingSteps: [
                "糙米洗净，加水煮熟",
                "鸡胸肉切块，用酱油、蜂蜜腌制30分钟",
                "热锅，加入橄榄油",
                "放入鸡胸肉煎至表面金黄",
                "盛出糙米饭，搭配鸡胸肉",
              ],
            },
          ];

          // 保存套餐数据
          for (const meal of meals) {
            await db.collection("meals").add({
              data: meal,
            });
          }

          result = {
            code: 200,
            success: true,
            data: {
              nutritionists: nutritionistQuery.data,
              ingredients: ingredientQuery.data,
              meals: await db
                .collection("meals")
                .get()
                .then((res) => res.data),
            },
            msg: "测试数据初始化成功",
          };
        } catch (err) {
          console.error("初始化测试数据失败:", err);
          result = {
            code: 500,
            success: false,
            msg: "初始化测试数据失败",
            data: null,
          };
        }
        break;
      // --- 添加：处理 saveUserInfo ---
      case "saveUserInfo": {
        console.log("处理 saveUserInfo 请求，参数:", JSON.stringify(event));
        // 假设小程序端调用时，用户信息在 event.userInfo 中
        const userInfoPayload = event.userInfo;
        if (!userInfoPayload) {
          console.error("saveUserInfo 请求缺少 userInfo 参数");
          result = { code: 400, msg: "缺少 userInfo 参数", data: null };
        } else {
          // 调用 saveUserInfo 子函数
          // 将 event 和 context 传递给子函数
          result = await saveUserInfo.main(event, context); // 直接传递 event
          console.log("saveUserInfo 处理结果:", JSON.stringify(result));
        }
        break;
      }
      // --- 添加结束 ---

      // 获取菜谱分类
      case "getRecipeCategories":
        console.log("处理getRecipeCategories请求");
        result = {
          code: 200,
          data: {
            list: [
              { id: "breakfast", name: "早餐" },
              { id: "lunch", name: "午餐" },
              { id: "dinner", name: "晚餐" },
              { id: "snack", name: "小食" },
              { id: "soup", name: "汤品" },
              { id: "vegetable", name: "素食" },
            ],
          },
          msg: "获取成功",
        };
        break;

      // 获取菜谱列表
      case "getRecipeList": {
        console.log("处理getRecipeList请求");
        // 从参数中获取分页和筛选条件
        const { page = 1, pageSize = 10, category = "" } = event.data || {};

        // 返回模拟数据
        const mockRecipes = [
          {
            id: 1,
            title: "营养早餐三明治",
            imageUrl: "/images/discovers/png/sanmingzhi.png",
            description: "健康美味的三明治，含有丰富的蛋白质和维生素",
            calories: 350,
            cookingTime: "15分钟",
            difficulty: "简单",
            category: "早餐",
          },
          {
            id: 2,
            title: "清炒时蔬",
            imageUrl: "/images/discovers/png/qingjiaoshishu.png",
            description: "低脂健康的素食选择，富含膳食纤维",
            calories: 200,
            cookingTime: "20分钟",
            difficulty: "简单",
            category: "素食",
          },
          {
            id: 3,
            title: "养生排骨汤",
            imageUrl: "/images/discovers/png/paigutang.png",
            description: "滋补养生的排骨汤，营养丰富",
            calories: 450,
            cookingTime: "60分钟",
            difficulty: "中等",
            category: "汤品",
          },
        ];

        // 根据分类筛选
        let filteredRecipes = category
          ? mockRecipes.filter((recipe) => recipe.category === category)
          : mockRecipes;

        result = {
          code: 200,
          data: {
            list: filteredRecipes,
            total: filteredRecipes.length,
            page,
            pageSize,
          },
          msg: "获取成功",
        };
        break;
      }
      // 搜索菜谱
      case "searchRecipes": {
        console.log("处理searchRecipes请求");
        const searchParams = event.data || {};
        const { keyword = "", category: searchCategory = "" } = searchParams;

        // 模拟搜索结果
        const searchResult = {
          id: 1,
          title: "健康" + keyword + "食谱",
          imageUrl: "/images/recipes/healthy.jpg",
          description: "这是一道健康美味的" + keyword + "菜品",
          calories: 300,
          cookingTime: "30分钟",
          difficulty: "简单",
          category: "健康菜",
        };

        result = {
          code: 200,
          data: {
            list: [searchResult],
            total: 1,
            page: searchParams.page || 1,
            pageSize: searchParams.pageSize || 10,
          },
          msg: "搜索成功",
        };
        break;
      }
      // 获取推荐套餐
      case "getRecommendedMeals": {
        console.log("处理getRecommendedMeals请求");

        result = {
          code: 200,
          data: {
            list: {
              breakfast: [
                {
                  id: 1,
                  name: "活力早餐套餐",
                  image: "/images/meals/breakfast1.png",
                  description: "营养均衡的健康早餐，提供一天所需能量",
                  calories: 350,
                  price: 29.9,
                  nutrition: {
                    protein: 20,
                    carbs: 40,
                    fat: 12,
                  },
                  type: "breakfast",
                },
                {
                  id: 2,
                  name: "轻食早餐套餐",
                  image: "/images/meals/breakfast2.png",
                  description: "低脂高纤维的清爽早餐",
                  calories: 280,
                  price: 25.9,
                  nutrition: {
                    protein: 15,
                    carbs: 35,
                    fat: 8,
                  },
                  type: "breakfast",
                },
              ],
              lunch: [
                {
                  id: 3,
                  name: "健康减脂午餐",
                  image: "/images/meals/lunch1.png",
                  description: "专为减脂人士定制的营养均衡午餐",
                  calories: 450,
                  price: 39.9,
                  nutrition: {
                    protein: 30,
                    carbs: 45,
                    fat: 15,
                  },
                  type: "lunch",
                },
                {
                  id: 4,
                  name: "能量午餐套餐",
                  image: "/images/meals/lunch2.png",
                  description: "提供充足能量的营养午餐",
                  calories: 520,
                  price: 42.9,
                  nutrition: {
                    protein: 35,
                    carbs: 50,
                    fat: 18,
                  },
                  type: "lunch",
                },
              ],
              dinner: [
                {
                  id: 5,
                  name: "轻享晚餐套餐",
                  image: "/images/meals/dinner1.png",
                  description: "易消化的健康晚餐",
                  calories: 380,
                  price: 35.9,
                  nutrition: {
                    protein: 25,
                    carbs: 35,
                    fat: 12,
                  },
                  type: "dinner",
                },
                {
                  id: 6,
                  name: "增肌能量晚餐",
                  image: "/images/meals/dinner2.png",
                  description: "高蛋白质、中等碳水的增肌晚餐",
                  calories: 650,
                  price: 45.9,
                  nutrition: {
                    protein: 40,
                    carbs: 40,
                    fat: 20,
                  },
                  type: "dinner",
                },
              ],
            },
            nutritionTips: [
              {
                id: 1,
                icon: "/images/tips/water.png",
                title: "补充水分",
                content: "建议每天饮水2000ml，保持身体水分平衡",
              },
              {
                id: 2,
                icon: "/images/tips/vegetables.png",
                title: "增加蔬菜摄入",
                content: "每餐应包含不同颜色的蔬菜，保证营养均衡",
              },
              {
                id: 3,
                icon: "/images/tips/protein.png",
                title: "优质蛋白",
                content: "选择瘦肉、鱼类、蛋类等优质蛋白，促进肌肉修复",
              },
              {
                id: 4,
                icon: "/images/tips/timing.png",
                title: "规律进餐",
                content: "保持规律的三餐时间，避免暴饮暴食",
              },
            ],
          },
          msg: "获取成功",
        };
        break;
      }
      // // 获取用户健康数据
      case "getUserHealthData": {
        console.log("处理getUserHealthData请求");
        const wxContext = cloud.getWXContext();
        const openid = wxContext.OPENID;

        if (!openid) {
          return { code: 401, msg: "无法获取用户 OpenID", data: null };
        }

        try {
          // 从 'users' 集合查询当前用户的记录
          const usersCollection = db.collection("users");
          const userRecordQuery = await usersCollection
            .where({
              _openid: openid,
            })
            .limit(1)
            .get();

          if (userRecordQuery.data.length > 0) {
            // 找到用户记录，返回数据
            const userHealthData = userRecordQuery.data[0];
            console.log(`找到用户 ${openid} 的健康数据:`, userHealthData);
            // **确保返回的字段名和类型与前端 updateUserInfo 函数期望的一致**
            // 例如: name, gender(number), age, height, weight, activityLevelId, dietPreferenceId
            result = {
              code: 200,
              // 直接返回数据库中的记录，前端需要的数据应该都在里面
              data: userHealthData,
              msg: "获取成功",
            };
          } else {
            // 没有找到用户记录
            console.log(`未找到用户 ${openid} 的健康数据记录`);
            result = {
              code: 404, // 或者使用其他合适的 code 表示用户未录入信息
              msg: "用户尚未录入健康信息",
              data: null,
            };
          }
        } catch (err) {
          console.error(`查询用户 ${openid} 健康数据失败:`, err);
          result = {
            code: 500,
            msg: "获取用户信息失败",
            data: null,
          };
        }
        break;
      }
      default:
        console.error("未知的type:", event.type);
        result = {
          code: 404,
          msg: "未找到对应的处理函数", // <----- 错误发生在这里，因为没有匹配到 saveUserInfo
          data: null,
        };
    }

    console.log("云函数返回结果:", JSON.stringify(result));
    return result;
  } catch (err) {
    console.error("云函数执行错误:", err);
    return {
      code: 500,
      msg: err.message || "服务器错误",
      data: null,
    };
  }
};
